import { deepClone } from "@/assets/utils/deepClone";
import router from "@/router/index";
export function cSearchData({ propData, emit, formEmitsObj, formPropsObj, dataed }: { dataed: any; formPropsObj: any; propData: CSuperFormPropsDataType; emit: (event: string, ...args: any[]) => void; formEmitsObj: any }) {
  return {
    cSearchOpt: propData.cSearchOpt,
    searching: dataed.value?.searching || false,
    formParams: propData.formParams,
    formEmitsObj,
    formPropsObj,
    emit
  };
}
export function cSearchFn(data: any) {
  const methods = {
    formValid: async function formValid() {
      let valided;
      await data.value.cFormRef.formRef.validate(async (valid: boolean) => {
        valided = valid;
      });
      return valided;
    },
    changeRadioed({ e, key, item, form }: changeRadioFormType) {
      data.value.formEmitsObj.changeRadio({ e, key, item, form });
      if (item.refresh) {
        methods.getListFn();
      }
    },
    getListFn: async () => {
      if (!(await methods.formValid())) return;
      data.value.searching = true;
      data.value.emit("getListFn");
      data.value.searching = false;
    },
    add: async () => {
      if (!(await methods.formValid())) return;
      if (!data.value.cSearchOpt?.notdialogAdd) return data.value.emit("showAdd", {});
      router.push(`${data.value.cSearchOpt.newRoute}/0`);
    },
    reset() {
      data.value.cFormRef?.resetfile(data.value.formParams);
      methods.getListFn();
    },
    initialFn() {
      let cSearchOpt = deepClone(data.value.formPropsObj.cformOpt);
      type ObjType = keyof typeof cSearchOpt.items;
      let item: ObjType;
      for (item in cSearchOpt?.items) {
        let itemOpt = cSearchOpt.items[item];
        if (!itemOpt.span) itemOpt.span = 6;
        itemOpt.formStyle = JSON.stringify({ marginRight: "30px", ...JSON.parse(itemOpt.formStyle || "{}") });
        if (!itemOpt.hasrules) itemOpt.hasrules = false;
      }
      nextTick(() => {
        data.value.emit("changeProps", { e: cSearchOpt, propsName: ["cformOpt"] });
      });
    }
  };
  methods.initialFn();
  return methods;
}
